package com.tpsix.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tpsix.controller.vm.UserQueryVM;
import com.tpsix.controller.vm.UserVM;
import com.tpsix.domain.SysUser;
import com.tpsix.service.SysUserService;
import com.tpsix.util.R;
import com.tpsix.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "users", tags = "系统用户资源")
@RestController
@RequestMapping("users")
@AllArgsConstructor
public class SysUserResource {

    private final SysUserService sysUserService;

    @PostMapping
    @ApiOperation(value = "添加用户")
    @PreAuthorize("hasAuthority('sys:user:add')")
    @ResponseStatus(HttpStatus.CREATED)
    public R<Boolean> add(@RequestBody UserVM userVM) {
        return R.ok(sysUserService.addOrUpdate(userVM));
    }

    @PutMapping
    @ApiOperation(value = "修改用户")
    @PreAuthorize("hasAuthority('sys:user:update')")
    @ResponseStatus(HttpStatus.CREATED)
    public R<Boolean> update(@RequestBody UserVM userVM) {
        return R.ok(sysUserService.addOrUpdate(userVM));
    }


    @DeleteMapping("{id:\\d+}")
    @ApiOperation(value = "删除用户")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public R<Boolean> delete(@PathVariable int id) {
        return R.ok(sysUserService.removeById(id));
    }

    @ApiOperation(value = "用户信息")
    @GetMapping("info")
    public R<SysUser> userInfo() {
        int userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.<SysUser>query().lambda()
                .select(SysUser::getUsername, SysUser::getAvatar)
                .eq(SysUser::getId, userId);
        SysUser user = sysUserService.getOne(queryWrapper);
        return R.ok(user);
    }

    @ApiOperation(value = "用户列表")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('sys:user:view')")
    public R<IPage<SysUser>> user(Page<?> page, UserQueryVM queryVM) {
        return R.ok(sysUserService.selectViewableUsers(page, queryVM));
    }

}
